package com.novel.download.utils;

import com.novel.download.controller.resp.SearchResp;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class ReadBookUtils {

    public static Document getDocument(String url) {
        System.out.println("url=" + url);
        try {
            return Jsoup.connect(url).validateTLSCertificates(false).get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Document postDocument(String url, Map<String, String> data) {
        System.out.println("url=" + url);
        try {
            return Jsoup.connect(url).method(Connection.Method.POST).data(data).post();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String split(String source, List<String> excludes) {
        if (StringUtils.hasLength(source)) {
            for (String exclude : excludes) {
                source = source.replaceAll(exclude, "");
                source = source.replaceAll(" ", "\n");
                source = source.replaceAll("\n {2}\n|\n {0}\n", "");
                source = source.replaceAll("\n", "\n  ");
            }
        }
        return source;
    }

    public static String searchRespToH5String(Map<String, List<SearchResp>> res) {
        if (CollectionUtils.isEmpty(res)) {
            return "结果为空";
        }
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, List<SearchResp>> entry : res.entrySet()) {
            sb.append(entry.getKey()).append("搜索结果：<br><br>");
            for (SearchResp searchResp : entry.getValue()) {
                sb.append(searchResp.toH5String()).append("<br><br>");
            }
            sb.append("---------------------------------------------<br>");
        }
        return sb.toString();
    }
}
